#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' main entry '
__author__ = 'pingwu you'

# 导入socket库:
import socket
def help111():
    # 创建一个socket:
    # AF_INET指定使用IPv4协议，如果要用更先进的IPv6，就指定为AF_INET6
    # SOCK_STREAM指定使用面向流的TCP协议
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 建立连接:
        s.connect(('www.baidu.com', 80))
        # 发送数据:
        s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n')
        # 接收数据:
        buffer = []
        while True:
            # 每次最多接收1k字节:
            d = s.recv(1024)
            if d:
                buffer.append(d)
            else:
                #直到recv()返回空数据，表示接收完毕
                break
        data = b''.join(buffer)
        header, html = data.split(b'\r\n\r\n', 1)
        print(header.decode('utf-8'))    
        print(html.decode("utf-8"))
    finally:
        if s:
            print("关闭socket")
            s.close()

def server():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('127.0.0.1', 9999))
        s.listen(5) #最大连接数
        print('Waiting for connection...')
        import threading
        while True:
            # 接受一个新连接:
            sock, addr = s.accept()
            # 创建新线程来处理TCP连接:
            t = threading.Thread(target=tcplink, args=(sock, addr))
            t.start()        
    finally:
        if s:
            print("关闭socket")
            s.close()

def tcplink(sock, addr):
    print('Accept new connection from %s:%s...' % addr)
    sock.send(b'Welcome!')
    import time
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('Hello reply, %s!' % data.decode('utf-8')).encode('utf-8'))
    sock.close()
    print('Connection from %s:%s closed.' % addr)

def tcpclient():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 建立连接:
    s.connect(('127.0.0.1', 9999))
    # 接收欢迎消息:
    print(s.recv(1024).decode('utf-8'))
    for data in [b'Michael', b'Tracy', '中国人民'.encode("utf-8")]:
        # 发送数据:
        s.send(data)
        print(s.recv(1024).decode('utf-8'))
    s.send(b'exit')
    s.close()